package smslogic

import (
	"huijing_mall/internal/cachebase"
	"huijing_mall/shared/common"
	"huijing_mall/shared/get_ctx_value"
	"huijing_mall/shared/kernel/ask"
	"huijing_mall/shared/kernel/hmErrors"
	"huijing_mall/variable"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func SmsLogic(c *gin.Context, mobile string) {
	dbs := get_ctx_value.GetDBS(c)
	var err error
	//每日5次
	countKey := common.StrPinJie(string(variable.CountKey), mobile)
	//五分钟有效
	timeoutKey := common.StrPinJie(string(variable.TimeoutKey), mobile)
	//压入队列 (只压次数) 后面清除用 不存在再压，避免重复删除
	if !cachebase.RedisExist(dbs.Rdb, countKey) {
		err = cachebase.LPushList(dbs.Rdb, string(variable.CountKey), countKey)
		if err != nil {
			ask.Errors(c, 500, hmErrors.ErrMsg("系统内部错误,请稍后再试."))
			return
		}
	}
	if cachebase.RedisExist(dbs.Rdb, timeoutKey) {
		ask.Errors(c, http.StatusOK, hmErrors.ErrMsg("请勿频繁发送"))
		return
	}
	//生成 验证码
	code := common.GetRandomString(6)

	//if err = dbs.Mq.Publish(variable.SendQu, []byte(mobile+"_"+code)); err != nil {
	//	logger.Info(fmt.Sprintf("发送消息到 %s 失败: %v", variable.SendQu, err))
	//} else {
	//	logger.Info(fmt.Sprintf("已发送消息到 %s: %s", variable.SendQu, mobile+"_"+code))
	//}
	if strings.Contains(mobile, "@") {
		//邮箱
		//to := []string{mobile}
		//err = common.SendEmail(to, code, "")
		//logger.Info("Email sent successfully!")
	} else {
		//第三方...
		//if !database.IhuY(mobile, code) {
		//	c.Data["sonic"] = map[string]interface{}{
		//		"message": "调用第三方库失败",
		//		"modelss":   http.StatusAccepted,
		//	}
		//	c.ServeJSON()
		//}
	}
	if err != nil {
		ask.Errors(c, http.StatusInternalServerError, hmErrors.ErrSystem("验证码发送失败"))
		return
	}

	res, err := cachebase.RedisGet(dbs.Rdb, countKey)
	if err != nil && res != "" {
		ask.Errors(c, http.StatusInternalServerError, hmErrors.ErrSystem("服务内部错误"))
		return
	}
	if res == "5" {
		ask.Errors(c, http.StatusOK, hmErrors.SmsOutOfGaugeErr)
		return
	}
	//暂时 使用 chan 进行凌晨清除
	variable.MbChan = make(chan string, 10)
	variable.MbChan <- mobile

	//存入redis
	cachebase.RedisIncr(dbs.Rdb, countKey)
	err = cachebase.RedisCodeTime(dbs.Rdb, timeoutKey, code, 5)
	if err != nil {
		ask.Errors(c, http.StatusInternalServerError, hmErrors.ErrSystem("服务内部错误"))
		return
	}
	ask.Success(c, map[string]interface{}{"smsCode": code, "id": common.RandomString(5)})
	return
}
